package com.zbkj.front.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.google.common.collect.Lists;
import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RSAPublicKeyNotificationConfig;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.partnerpayments.nativepay.model.Transaction;
import com.wechat.pay.java.service.payments.nativepay.NativePayService;
import com.wechat.pay.java.service.payments.nativepay.model.Amount;
import com.wechat.pay.java.service.payments.nativepay.model.PrepayRequest;
import com.wechat.pay.java.service.payments.nativepay.model.PrepayResponse;
import com.zbkj.common.enums.OrderStatusEnum;
import com.zbkj.common.enums.OrderTypeEnum;
import com.zbkj.common.exception.CommonException;
import com.zbkj.common.model.order.OrderDetail;
import com.zbkj.common.model.order.OrderInfo;
import com.zbkj.common.model.user.User;
import com.zbkj.common.request.order.ClientOrderSaveRequest;
import com.zbkj.common.response.order.OrderSucceResponse;
import com.zbkj.front.config.WechatPayConfig;
import com.zbkj.front.service.OrderHandleService;
import com.zbkj.front.service.PaymentService;
import com.zbkj.service.service.order.OrderDetailService;
import com.zbkj.service.service.order.OrderInfoService;
import com.zbkj.service.service.user.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class WechatPaymentService implements PaymentService {
    @Resource
    private NativePayService nativePayService;
    @Resource
    private WechatPayConfig wechatPayConfig;


    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private UserService userService;
    @Autowired
    private OrderDetailService orderDetailService;


    @Autowired
    private OrderHandleService orderHandleService;


    @Override
    public String pay(Map<String, Object> params) throws AlipayApiException {
        return null;
    }

    @Override
    public OrderSucceResponse wxpay(Map<String, Object> params) {
        OrderSucceResponse succeResponse = orderHandleService.orderSave((ClientOrderSaveRequest) params.get("saveRequest"));
        OrderInfo orderInfo = orderInfoService.getOrderInfo(null, succeResponse.getOrderNo());


        Amount amount = new Amount();
//        amount.setTotal(BigDecimal.ONE.intValue()); // 金额，单位为分
        amount.setTotal(orderInfo.getTotalAmount().multiply(BigDecimal.valueOf(100)).intValue()); // 金额，单位为分

        PrepayRequest request = new PrepayRequest();
        request.setAppid(wechatPayConfig.getAppid());
        request.setMchid(wechatPayConfig.getMchId());
        //商品描述
        request.setDescription(orderInfo.getTfremark());
        //商户订单号
//        request.setOutTradeNo("20250424103412002");
        request.setOutTradeNo(succeResponse.getOrderNo());
        //回调地址
        request.setNotifyUrl(wechatPayConfig.getNotifyUrl());
        //金额
        request.setAmount(amount);
        //生成的链接过期时间
        //request.setTimeExpire("");

        PrepayResponse prepay = nativePayService.prepay(request);

        // 将二维码地址设置到 OrderSucceResponse
        succeResponse.setOrderurl(prepay.getCodeUrl()); // 确保 OrderSucceResponse 有 setOrderurl 方法

        return succeResponse;
    }

    @Override
    public String callback(HttpServletRequest request, HttpServletResponse response) {

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()))) {

            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            String body = sb.toString();
            //构造RequestParam
            RequestParam requestParam = new RequestParam.Builder()
                    //微信支付平台证书的证书序列号
                    .serialNumber(request.getHeader("Wechatpay-Serial"))
                    //随机字符串（签名中的随机数）
                    .nonce(request.getHeader("Wechatpay-Nonce"))
                    //签名值（应答的微信支付签名）
                    .signature(request.getHeader("Wechatpay-Signature"))
                    //时间戳（签名中的时间戳）
                    .timestamp(request.getHeader("Wechatpay-Timestamp"))
                    //请求参数
                    .body(body)
                    .build();

            log.info("------微信支付收到支付通知------,报文：【{}】", JSONUtil.toJsonStr(requestParam));
            NotificationConfig config = new RSAPublicKeyNotificationConfig.Builder()
                    .publicKeyFromPath(wechatPayConfig.getPublicKeyPath())
                    .publicKeyId(wechatPayConfig.getPublicKey())
                    .apiV3Key(wechatPayConfig.getApiV3Key())
                    .build();


            // 初始化 NotificationParser
            NotificationParser parser = new NotificationParser(config);


            //验证和解析请求体
            Transaction transaction = parser.parse(requestParam, Transaction.class);
            log.info("wx callback response:{}", JSON.toJSONString(transaction));


            //订单号、微信支付单号
            String outTradeNo = transaction.getOutTradeNo();
            String transactionId = transaction.getTransactionId();


            //TODO 处理业务逻辑

            OrderInfo orderInfo = orderInfoService.getOrderInfoByOrderNo(outTradeNo);
            Integer status = orderInfo.getOrderType();
            if (!OrderStatusEnum.isOrderStatus1(orderInfo.getOrderStatus())) {
                throw new CommonException("订单状态已变更，请刷新后重试");
            }

            User user = userService.getUserById(orderInfo.getUserId());
            userService.userValidCheck(user);
            List<OrderDetail> orderDetailList = orderDetailService.getListByOrderIds(Lists.newArrayList(orderInfo.getId()));
            if (OrderTypeEnum.isType1(orderInfo.getOrderType())) {
                //申请报告订单开通处理
                orderHandleService.orderStatusUpdate(orderInfo, status, Lists.newArrayList(OrderStatusEnum.ORDER_STATUS1.getStatus()), null);
            } else {
                //年卡流量包订单开通处理
                orderHandleService.orderApprovalOpen(user, orderInfo, orderDetailList);
            }


            //响应微信服务器
            response.setStatus(HttpServletResponse.SC_OK);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", "SUCCESS");
            jsonObject.put("message", "成功");
            return jsonObject.toString();
        } catch (IOException e) {
            response.setStatus(500);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", "ERROR");
            jsonObject.put("message", "签名失败");
            log.error("微信回调处理失败", e);
            return jsonObject.toString();
        }
    }
}
